package demo02_work_queue;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @Description 工作队列模式的消息生产者
 * @Author shihan
 * @Date 2020/12/20 10:38
 * @Version 1.0
 */
public class WQProducer {

    public static final String QUEUE_NAME = "queue.qname";
    public static final String EXCHANGE_NAME = "exc.ename";
    public static final String ROUTING_KEY = "RK.WQ";

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri("amqp://root:123456@192.168.66.129:5672/%2f");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明一个 Queue 队列（有则不作处理，没有队列则创建一个队列）
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        // 声明一个 Exchange 交换器
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT,true);

        // 绑定 Exchange 和 Queue：将 Exchange 和 Queue 绑定使用 queueBind；将 Exchange 和 Exchange 绑定使用 exchangeBind ；
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,ROUTING_KEY);

        // 循环进行消息的生产发送
        for (int i = 1; i <= 15; i++) {
            channel.basicPublish(EXCHANGE_NAME,ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN,("生产者循环发送消息：" + i).getBytes("utf-8"));
        }

        // 关闭连接：生产环境使用连接池技术！
        channel.close();
        connection.close();

    }

}
